﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPNETPerformance.App_BusinessLogic.BasePages;
using ASPNETPerformance.App_BusinessLogic.Helpers;
using ASPNETPerformance.App_BusinessLogic.Utils;
using ASPNETPerformance.App_BusinessLogic.ViewState;

namespace ASPNETPerformance._01_ViewState {
    public partial class OnTheServer : BasePage {
        protected void Page_Load( object sender, EventArgs e ) {

        }

        protected override void SavePageStateToPersistenceMedium( object pageViewState ) {
            if ( CommonHelper.GetCookieBool( "IsOnTheServer" ) ) {
                MemoryStream ms = new MemoryStream();

                LosFormatter m_formatter = new LosFormatter();

                m_formatter.Serialize( ms, pageViewState );

                ms.Position = 0;

                StreamReader sr = new StreamReader( ms );

                string viewStateString = sr.ReadToEnd();

                byte[] ViewStateBytes = Convert.FromBase64String( viewStateString );

                ViewStateBytes = ViewStateCompression.Compress( ViewStateBytes );

                Session[ "ViewState" ] = Convert.ToBase64String( ViewStateBytes );

                ms.Close();

                return;
            }
            else {
                base.SavePageStateToPersistenceMedium( pageViewState );
            }
        }

        // 序列化ViewState
        protected override object LoadPageStateFromPersistenceMedium() {
            if ( CommonHelper.GetCookieBool( "IsOnTheServer" ) ) {
                object viewStateBag;

                string m_viewState = ( string )Session[ "ViewState" ];

                byte[] ViewStateBytes = Convert.FromBase64String( m_viewState );

                ViewStateBytes = ViewStateCompression.Decompress( ViewStateBytes );

                LosFormatter m_formatter = new LosFormatter();

                try {
                    viewStateBag = m_formatter.Deserialize( Convert.ToBase64String( ViewStateBytes ) );
                }
                catch ( Exception ex ) {
                    //Log.Insert( "页面Viewtate是空." );
                    viewStateBag = string.Empty;
                }
                return viewStateBag;
            }
            else {
                return base.LoadPageStateFromPersistenceMedium();
            }
        }
    }
}